package com.base.common.cfg;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

/**
 * @author Davin qsd
 * 
 */
public abstract class PropertiesAbstract {

	public PropertiesHelper props;

	abstract public String getPropertiesFileName();

	private void loadProperties() {
		try {
			System.out.println("Load [generator.properties] from classpath");
			props = new PropertiesHelper(loadAllPropertiesByClassLoader(getPropertiesFileName()));

			for (Iterator it = props.entrySet().iterator(); it.hasNext();) {
				Map.Entry entry = (Map.Entry) it.next();
				System.out.println("[Property] " + entry.getKey() + "=" + entry.getValue());
			}

			System.out.println();

		} catch (IOException e) {
			throw new RuntimeException("Load Properties error", e);
		}
	}

	public Properties getProperties() {
		return getHelper().getProperties();
	}

	private PropertiesHelper getHelper() {
		if (props == null)
			loadProperties();
		return props;
	}

	public String getProperty(String key, String defaultValue) {
		return getHelper().getProperty(key, defaultValue);
	}

	public String getProperty(String key) {
		return getHelper().getProperty(key);
	}

	public String getRequiredProperty(String key) {
		return getHelper().getRequiredProperty(key);
	}

	public int getRequiredInt(String key) {
		return getHelper().getRequiredInt(key);
	}

	public boolean getRequiredBoolean(String key) {
		return getHelper().getRequiredBoolean(key);
	}

	public String getNullIfBlank(String key) {
		return getHelper().getNullIfBlank(key);
	}

	public void setProperty(String key, String value) {
		getHelper().setProperty(key, value);
	}

	public void setProperties(Properties v) {
		props = new PropertiesHelper(v);
	}

	public Properties loadAllPropertiesByClassLoader(String resourceName) throws IOException {
		Properties properties = new Properties();
		Enumeration urls = PropertiesAbstract.class.getClassLoader().getResources(resourceName);
		while (urls.hasMoreElements()) {
			URL url = (URL) urls.nextElement();
			InputStream input = null;
			try {
				URLConnection con = url.openConnection();
				con.setUseCaches(false);
				input = con.getInputStream();
				properties.load(input);
			} finally {
				if (input != null) {
					input.close();
				}
			}
		}
		return properties;
	}
}
